package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.feign.article.IArticleClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.CheckNewDto;
import com.heima.model.wemedia.dtos.NewsDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.model.wemedia.vos.NewsVo;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: JW
 * @Description: TODO
 * @DateTime: 2022-02-11 20:47
 **/
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews>  implements WmNewsService {

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    private WmMaterialService wmMaterialService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmChannelService wmChannelService;


    @Override
    public ResponseResult getList(WmNewsPageReqDto wmNewsPageReqDto) {

        //参数校验
        if (ObjectUtils.isEmpty(wmNewsPageReqDto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //分页条件
        Page<WmNews> wmNewsPage = new Page<>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());

        //查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //关键字查询
        lambdaQueryWrapper.like(StringUtils
                .isNotEmpty(wmNewsPageReqDto.getKeyword()),WmNews::getTitle,wmNewsPageReqDto.getKeyword());

        //频道查询
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getChannelId() != null,
                WmNews::getChannelId,wmNewsPageReqDto.getChannelId());

        //时间查询
        lambdaQueryWrapper.between(
                wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null,
                WmNews::getCreatedTime, wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate());

        //状态查询
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getStatus() != null,
                WmNews::getStatus,wmNewsPageReqDto.getStatus());

        //提交时间倒叙排序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //查询
        page(wmNewsPage,lambdaQueryWrapper);

        ResponseResult responseResult = new PageResponseResult((int)wmNewsPage.getPages(),
                (int)wmNewsPage.getSize(),(int)wmNewsPage.getTotal());

        return responseResult.ok(wmNewsPage.getRecords());
    }

    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {

        //参数校验
        if (ObjectUtils.isEmpty(wmNewsDto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //新建文章
        WmNews wmNews = new WmNews();

        //封面问题 并拿到内容图片集合
        List<String> imageList = getImageList(wmNewsDto);

        //更新或者修改
        updateAndSave(wmNews,wmNewsDto);

        //如果是草稿 就不需要保存与素材表关系
        if (wmNewsDto.getStatus() == 0){
            return ResponseResult.okResult(wmNews.getId());
        }

        //如果没有图片可以直接退出
        if (imageList.isEmpty() && ObjectUtils.isEmpty(wmNewsDto.getImages())){
            return ResponseResult.okResult(wmNews.getId());
        }

        //保存图片与素材关系表
        //保存内容图片
        if (!imageList.isEmpty()){

            saveWmNewsMaterialList(wmNews, imageList);

        }
        //保存封面图片
        if (!ObjectUtils.isEmpty(wmNewsDto.getImages())){
            saveWmNewsMaterialList(wmNews, wmNewsDto.getImages());
        }

        return ResponseResult.okResult(wmNews.getId());
    }

    /**
     * @param wmNewsDto
     * @Author: JW
     * @Description: TODO 上下架
     * @Date: 20:34 2022-02-17
     * @Param: [wmNewsDto]
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {

        WmNews wmNews = getById(wmNewsDto.getId());

        //判断文章是否存在
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断是否处于已发布状态
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //修改状态
        wmNews.setEnable(wmNewsDto.getEnable());
        updateById(wmNews);

        //发送消息
        if (wmNews.getArticleId() != null){

            //组装发送消息
            HashMap<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", wmNews.getEnable());

            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param newsDto
     * @Author: JW
     * @Description: TODO 查询
     * @Date: 21:33 2022-02-18
     * @Param: [wmNewsDto]
     * @return: com.heima.model.common.dtos.PageResponseResult
     */
    @Override
    public PageResponseResult find(NewsDto newsDto) {

        //分页条件
        Page<WmNews> page = new Page<>(newsDto.getPage(),newsDto.getSize());

        //查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery(WmNews.class)
                .eq(newsDto.getStatus() != null && newsDto.getStatus() != 0,
                        WmNews::getStatus, newsDto.getStatus())
                .like(StringUtils.isNotEmpty(newsDto.getTitle()), WmNews::getTitle, newsDto.getTitle());

        //分页查询
        page(page,queryWrapper);

        PageResponseResult result = new PageResponseResult(newsDto.getPage(),
                newsDto.getSize(), (int) page.getTotal());

        List<WmNews> wmNewsList = page.getRecords();

        List<Integer> userIds = new ArrayList<>();

        if (!ObjectUtils.isEmpty(wmNewsList)){
            //拿到所有的用户id
            userIds = wmNewsList.stream().map(WmNews::getUserId).collect(Collectors.toList());
        }

        //拿到所有的用户信息
        Map<Integer, WmUser> userMap = wmUserService.listByIds(userIds).stream()
                .collect(Collectors.toMap(WmUser::getId, Function.identity()));

        //返回结果集
        ArrayList<NewsVo> newsVos = new ArrayList<>();

        //遍历所有文章
        for (WmNews wmNews : wmNewsList) {

            //拿到对应的用户
            WmUser wmUser = userMap.get(wmNews.getUserId());

            if (wmNews != null){

                NewsVo newsVo = new NewsVo();
                //补全数据
                BeanUtils.copyProperties(wmNews,newsVo);
                newsVo.setAuthorName(wmUser.getName());

                newsVos.add(newsVo);
            }
        }

        result.setData(newsVos);

        return result;
    }

    /**
     * @param checkNewDto
     * @Author: JW
     * @Description: TODO 驳回（文章审核不通过）
     * @Date: 11:26 2022-02-19
     * @Param: [checkNewDto]
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult authFail(CheckNewDto checkNewDto) {

        //参数校验
        if (ObjectUtils.isEmpty(checkNewDto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询出文章
        WmNews wmNews = getById(checkNewDto.getId());

        if (!ObjectUtils.isEmpty(wmNews)){

            //补全参数
            wmNews.setStatus(checkNewDto.getStatus());
            wmNews.setReason(checkNewDto.getMsg());

            //修改文章
            updateById(wmNews);

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param checkNewDto
     * @Author: JW
     * @Description: TODO 通过（文章审核通过）
     * @Date: 11:36 2022-02-19
     * @Param: [checkNewDto]
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult authPass(CheckNewDto checkNewDto) {

        //参数校验
        if (ObjectUtils.isEmpty(checkNewDto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = getById(checkNewDto.getId());

        if (!ObjectUtils.isEmpty(wmNews)){

            //修改文章状态
            wmNews.setStatus(checkNewDto.getStatus());

            //修改文章
            updateById(wmNews);
        }

        //远程调用app端将文章上架
        //补全参数
        ArticleDto dto = new ArticleDto();
        //拷贝参数
        BeanUtils.copyProperties(wmNews,dto);

        //查询发布用户
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());

        //查询文章类型
        WmChannel channel = wmChannelService.getById(wmNews.getChannelId());

        dto.setChannelName(channel.getName());
        dto.setAuthorName(wmUser.getName());
        dto.setLayout(wmNews.getType());
        dto.setAuthorId(Long.valueOf(wmNews.getUserId()));

        ResponseResult responseResult = iArticleClient.saveArticle(dto);

        if (responseResult.getData() != null){
            //拿到app文章id
            Long articleId = (Long) responseResult.getData();

            wmNews.setArticleId(articleId);
            wmNews.setStatus((short) 9);

            updateById(wmNews);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param id
     * @Author: JW
     * @Description: TODO 查看单个文章
     * @Date: 14:50 2022-02-19
     * @Param: [id]
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult getOneNews(Integer id) {

        //参数校验
        if (ObjectUtils.isEmpty(id)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //返回结果
        NewsVo newsVo = new NewsVo();

        //查询文章
        WmNews wmNews = getById(id);

        //查询作者
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());

        //数据拷贝
        BeanUtils.copyProperties(wmNews,newsVo);
        newsVo.setAuthorName(wmUser.getName());

        return ResponseResult.okResult(newsVo);
    }


    /**
     * @Author: JW
     * @Description:  TODO 保存图片与素材关系
     * @Date: 21:43 2022-02-12
     * @Param: [wmNews, imageList]
     * @return: void
    **/
    private void saveWmNewsMaterialList(WmNews wmNews, List<String> imageList) {
        //查询所有素材
        List<WmMaterial> materialList = wmMaterialService
                .list(Wrappers.lambdaQuery(WmMaterial.class).in(WmMaterial::getUrl, imageList));

        //查询到素材id
        List<Integer> wmMaterialIds = materialList.stream()
                .map(WmMaterial::getId).collect(Collectors.toList());

        //关联集合
        List<WmNewsMaterial> wmNewsMaterialList = new ArrayList<>();

        //对象集合
        for (int i = 0; i < wmMaterialIds.size(); i++) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setMaterialId(wmMaterialIds.get(i));
            wmNewsMaterial.setType((short) 0);
            wmNewsMaterial.setOrd((short) (i+1));
            wmNewsMaterialList.add(wmNewsMaterial);
        }
        wmNewsMaterialService.saveBatch(wmNewsMaterialList);
    }

    /**
     * @Author: JW
     * @Description:  TODO 内容图片集合 && 解决自动封面图片
     * @Date: 21:04 2022-02-12
     * @Param: [wmNewsDto] 内容图片集合
     * @return: java.util.List<java.lang.String>
    **/
    private List<String> getImageList(WmNewsDto wmNewsDto) {
        //图片集合
        List<String> imageList = new ArrayList<>();

        //将文章内容转化为map对象的集合
        List<Map> contentMap = JSON.parseArray(wmNewsDto.getContent(), Map.class);

        //存储图片
        for (Map content : contentMap) {
            if ("image".equals(content.get("type"))){
                imageList.add(content.get("value").toString());
            }
        }

        //如果此时作者选择的是自动封面图片(内容中含有图片时) 就需要我们存入封面图片
        if (wmNewsDto.getType() == -1 && imageList.size() > 0){

            //内容图片大于三时
            if (imageList.size() >= 3){
                //拿前三张图片做封面图
                wmNewsDto.setImages(imageList.stream().limit(3).collect(Collectors.toList()));
                //修改为三图
                wmNewsDto.setType((short) 3);
            }else {
                //拿第一张图片做封面图
                wmNewsDto.setImages(imageList.stream().limit(1).collect(Collectors.toList()));
                //修改为单图
                wmNewsDto.setType((short) 1);
            }
        }
        return imageList;
    }

    /**
     * @Author: JW
     * @Description:  TODO 修改或者新增
     * @Date: 21:11 2022-02-12
     * @Param: [wmNewsDto]
     * @return: void
    **/
    private void updateAndSave(WmNews wmNews,WmNewsDto wmNewsDto) {

        //拷贝参数
        BeanUtils.copyProperties(wmNewsDto,wmNews);

        //将集合转化为string
        String images = StringUtils.join(wmNewsDto.getImages().toArray(), ",");

        //补全参数
        if(StringUtils.isNotBlank(images)){
            wmNews.setImages(images);
        }

        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        //不为空时,说明是修改
        if (wmNewsDto.getId() != null){
            //直接删除有关素材表
            wmNewsMaterialService.remove(Wrappers.lambdaQuery(WmNewsMaterial.class)
                    .eq(WmNewsMaterial::getNewsId, wmNewsDto.getId()));

            //更新文章
            updateById(wmNews);

        }else {
            //新增文章
            save(wmNews);
        }
    }

}
